package models;

import java.io.Serializable;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import utils.ReflectionUtils;

/**
 * 统一定义id的entity基类.
 * 
 * @author sunchaohui
 */

@MappedSuperclass
public abstract class IdEntity implements Serializable {
	
	public String toXML() {
		XStream sm = new XStream(new DomDriver());
		return sm.toXML(this);
	}
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer id;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Transient
	public int hashCode = Integer.MIN_VALUE;

	public boolean equals(Object object) {
		if (null == object)
			return false;
		if (!(object.getClass().getName().equals(this.getClass().getName())))
			return false;
		else {
			Integer object_id = (Integer) ReflectionUtils.getFieldValue(object,"id");
			if (null == this.getId() || null == object_id)
				return false;
			else
				return (this.getId().intValue() == object_id.intValue());
		}
	}
	
	public int hashCode() {
		if (Integer.MIN_VALUE == this.hashCode) {
			if (null == this.getId())
				return super.hashCode();
			else {
				String hashStr = this.getClass().getName() + ":"
						+ this.getId().hashCode();
				this.hashCode = hashStr.hashCode();
			}
		}
		return this.hashCode;
	}
	
	public String toString() {
		return super.toString();
	}
}
